# coding: utf-8
import re
from time import sleep

import pymysql
import easygui
import pygame
import requests
from pygame.locals import *
from xpinyin import Pinyin
import analyze
import datetime
#import voice

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456',
                       database='weather_forecast', charset='utf8')
cursor = conn.cursor()

forecastLists = []

def renderText(font, size, text, pos, canvas, type='file', file=r'tool\fonts\FZMW.ttf'):
    if type == 'local':
        textfont = pygame.font.SysFont(font, size)
        TF = textfont.render(text, True, (255, 255, 255))
        canvas.blit(TF, pos)
    else:
        textfont = pygame.font.Font(file, size)
        TF = textfont.render(text, True, (255, 255, 255))
        canvas.blit(TF, pos)
# Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4083.0 Safari/537.36 Edg/82.0.458.0

def getcitypinyin(str):
    pinyin = Pinyin()
    result = pinyin.get_pinyin(str, '')
    return result


class getweater(object):

    def __init__(self):
        self.city = '广州'
        self.citypinyin = getcitypinyin(self.city)
        self.url = "https://m.tianqi.com/" + self.citypinyin + '/'
        self.headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4083.0 Safari/537.36 Edg/82.0.458.0'
        }

    def gettodayweater(self):
        repon = requests.get(self.url, headers=self.headers)
        repon.encoding = 'utf-8'
        html = repon.text
        # print(repon, html)
        regdate = '<div class="date">(.*?)</div>'
        self.date = re.findall(regdate, html)[0]
        regnow = '<dd class="now">(.*?)<i>°C</i></dd>'
        self.temp = '当前温度：' + re.findall(regnow, html)[0] + '°C'
        # print(self.now)
        regtxt = '<dd class="txt">(.*?)</dd>'
        self.wea = '今日天气：' + re.findall(regtxt, html)[0]
        # print(self.txt)
        regb1 = '<span class="b2"><i></i>(.*?)</span>'
        self.shi = re.findall(regb1, html)[0]
        # print(self.b1)
        regb2 = '<span class="b3"><i></i>(.*?)</span>'
        self.feng = re.findall(regb2, html)[0]

def getFutureDate():
    today = datetime.datetime.now()
    for i in range(1, 6):
        offset = datetime.timedelta(days = i)
        re_date = (today + offset).strftime('%Y-%m-%d')
        external = analyze.forecast(re_date)
        forecastLists.append(external.copy())
        print(forecastLists)

def getDateStr(date):
   year = str(re.findall("\d{2}", date)[0]) + str(re.findall("\d{2}", date)[1])
   mouth = str(re.findall("\d{2}", date)[2])
   day = str(re.findall("\d{2}", date)[3])
   date = year + '-' + mouth + '-' + day
   return date

def playDateStr(date):
    year = str(re.findall("\d{2}", date)[0]) + str(re.findall("\d{2}", date)[1])
    mouth = str(re.findall("\d{2}", date)[2])
    day = str(re.findall("\d{2}", date)[3])
    dateVoice = year + '年' + mouth + '月' + day + '日'
    return dateVoice


class GlobalVar(object):
    weather = getweater()
GlobalVar.weather.gettodayweater()

def threewindow():
    getFutureDate()
    pygame.init()
    bg = pygame.image.load(r"tool\images\weather3.jpg")
    canvas = pygame.display.set_mode((1050, 660))

    def handleEvent():
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                return True
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                mx, my = pygame.mouse.get_pos()
                print(mx, my)
                if 10 <= mx <= 50 and 10 <= my <= 50:
                    pygame.quit()
                    localweatherbg()
                    return True
    while True:
        # print(forecastList)
        canvas.blit(bg, (0, 0))
        for i in range(5):
            x = 5
            y = 84 + 95 * i
            renderText('simhei', 25, forecastLists[i].get('日期'), (x, y), canvas, "file", r'tool\fonts\PingFang Bold.ttf')
            renderText('simhei', 25, forecastLists[i].get('预测天气'), (x + 180, y), canvas, "file", r'tool\fonts\PingFang Bold.ttf')
            renderText('simhei', 25, forecastLists[i].get('预测风向'), (x, y + 40), canvas, "file", r'tool\fonts\PingFang Bold.ttf')
            renderText('simhei', 25, '空气质量：' + forecastLists[i].get('预测最高温度'), (x + 220, y + 40), canvas, "file", r'tool\fonts\PingFang Bold.ttf')
        pygame.display.update()
        for i in range(5):
            cityss = forecastLists[i].get('城市')
            datess = forecastLists[i].get('日期')
            weathss = forecastLists[i].get('预测天气')
            highTemss = forecastLists[i].get('预测最高温度')
            lowTemss = forecastLists[i].get('预测最低温度')
            windss = forecastLists[i].get('预测风向')
            text = '预测' + cityss + '在' + playDateStr(datess) + '，天气为' + weathss + '，预测最高温度为，' + highTemss + '摄氏度，' + '预测最低温度为，' + lowTemss + '摄氏度，' + '风向为' +windss
            voice.allplay(text)
            sleep(30000)
        if handleEvent():
            break

def localweatherbg():
    pygame.init()
    bg = pygame.image.load("tool/images/weather2.jpg")
    canvas = pygame.display.set_mode((1050, 660))

    def handleEvent():
        event = pygame.event.get()
        for i in event:
            if i.type == QUIT:
                pygame.quit()
                return True
            elif i.type == MOUSEBUTTONDOWN and i.button == 1:
                x, y = pygame.mouse.get_pos()
                print(x, y)
                if 410 <= x <= 650 and 450 <= y <= 500:
                    pygame.quit()
                    print("跳转中")
                    print("完成")
                    threewindow()
                    return True
                if 423 <= x <= 627 and 538 <= y <= 592:
                    GlobalVar.weather.city = easygui.enterbox('请输入城市名称：')
                    GlobalVar.weather.citypinyin = getcitypinyin(GlobalVar.weather.city)
                    GlobalVar.weather.url = "https://m.tianqi.com/" + GlobalVar.weather.citypinyin + '/'
                    GlobalVar.weather.gettodayweater()
                    getFutureDate()
                    localweatherbg()

    while True:
        canvas.blit(bg, (0, 0))
        GlobalVar.weather.gettodayweater()
        renderText('fangsong', 30, GlobalVar.weather.date, (249, 120), canvas)
        renderText('simhei', 50, GlobalVar.weather.city + '今日天气', (360, 5), canvas, file=r'tool\fonts\PingFang Bold.ttf')
        renderText('simhei', 30, GlobalVar.weather.temp, (251, 158), canvas)
        renderText('simhei', 30, GlobalVar.weather.wea, (251, 192), canvas)
        renderText('simhei', 40, GlobalVar.weather.feng, (254, 230), canvas)
        pygame.display.update()
        # text =  GlobalVar.weather.city + '在' + GlobalVar.weather.date  + GlobalVar.weather.wea  + '风向为' + GlobalVar.weather.feng
        # voice.allplay(text)
        if handleEvent():
            break


def start_bg():
    canvas = pygame.display.set_mode((1050, 660))
    pygame.display.set_caption("HR天气预报为您服务")
    bg = pygame.image.load("tool/images/weather1.jpg")

    def handleEvent():
        event = pygame.event.get()
        for i in event:
            if i.type == QUIT:
                pygame.quit()
                return True
            if i.type == MOUSEBUTTONDOWN and i.button == 1:
                mx, my = pygame.mouse.get_pos()
                print(mx, my)
                # 根据按下的位置判断点了哪个按钮
                if 10 <= mx <= 50 and 10 <= my <= 50:
                    pygame.quit()
                    print("退出成功")
                elif 550 <= my <= 610 and 760 <= mx <= 970:
                    pygame.quit()
                    print("进入天气预报中")
                    print("进入成功")
                    localweatherbg()
                    return True

    while True:
        canvas.blit(bg, (0, 0))
        pygame.display.update()
        if handleEvent():
            break


start_bg()
